package cn.wgx.commons.util;


import cn.wgx.modules.base.web.EMailController;
import cn.wgx.modules.base.web.SMSController;

import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Date;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

/**
 * 图片验证码
 */
public class ValidateCodeImageUtil {


    private static int w = 70;
    private static int h = 26;
    private static int codeLen = 4;

    public static boolean validCodeEmail(HttpSession session, String code,
                                    Map<String,Object> map,
                                    boolean isDisable){
        session.setAttribute(SMSController.SESSION_BIND_IS_SMS, "email");
        return validCode(session,code,map,isDisable, null);
    }

    public static boolean validCodePhone(HttpSession session, String code,
                                         Map<String,Object> map,
                                         boolean isDisable){
        session.setAttribute(SMSController.SESSION_BIND_IS_SMS, "sms");
        return validCode(session,code,map,isDisable,null);
    }

    public static boolean validCode(HttpSession session, String code,
                                    Map<String, Object> map,
                                    boolean isDisable){
        return validCode(session,code,map,isDisable,null);
    }
    /**
     * 检测验证码正确
     * @param session
     * @param code
     * @param map
     * @param isDisable 删除session中验证码
     * @param vdevnum 接收验证码的手机或邮箱地址
     * @return
     */
    public static boolean validCode(HttpSession session, String code,
                                    Map<String, Object> map,
                                    boolean isDisable, String vdevnum){
        Object vCodeType = session.getAttribute(SMSController.SESSION_BIND_IS_SMS);
        if(vCodeType == null){
            map.put("success", false);
            map.put("errorMsg", "验证码错误");
            return false;
        }
        String attributName, attributDate, devNum;
        if("sms".equals(vCodeType)){
            attributName = SMSController.SESSION_BIND_KEY_PHONE;
            attributDate = SMSController.SESSION_BING_KEY_DATE;
            devNum = SMSController.SESSION_BIND_SEND_PHONE;
        } else {
            attributName = EMailController.SESSION_BIND_KEY_EMAIL;
            attributDate = EMailController.SESSION_BIND_KEY_DATE;
            devNum = EMailController.SESSION_BIND_SEND_EMAIL;
        }
        Object o = session.getAttribute(attributName);
        Object d = session.getAttribute(attributDate);
        boolean b = false;
        String errorMsg = "";
        if(code != null
                && o != null && o instanceof String
                && d != null && d instanceof Date){
            Date date = (Date)d;
            if((new Date().getTime() - date.getTime()) > (10*60*1000)){
                errorMsg = "验证码已过期.";
            }else if(!code.equals(o.toString())){
                errorMsg = "验证码错误.";
            }else if(vdevnum != null && vdevnum.equals(devNum)){
                errorMsg = "非正确绑定号码.";
            }else{
                if(isDisable){
                    session.setAttribute(attributName, UUID.randomUUID());
                }
                b = true;
            }
        }else{
            errorMsg = "未知验证码错误.";
        }
        map.put("success", b);
        map.put("msg", errorMsg);
        return b;
    }

    /**
     *  获取随机字符码
     * @return
     */
    public String createVCode(){
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < codeLen; i++) {
            String r = String.valueOf(codeSeq[random.nextInt(codeSeq.length)]);
            s.append(r);
        }
        return s.toString();
    }

    public BufferedImage createImage(String code)  {
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        /*
         * 生成背景
         */
        createBackground(g);
        /*
         * 生成字符
         */
        createCharacter(g, code);

        g.dispose();

        return image;

    }

    private Color getRandColor(int fc,int bc) {
        int f = fc;
        int b = bc;
        Random random = new Random();
        if(f>255) {
            f=255;
        }
        if(b>255) {
            b=255;
        }
        return new Color(f+random.nextInt(b-f),f+random.nextInt(b-f),f+random.nextInt(b-f));
    }

    private void createBackground(Graphics g) {
        // 填充背景
        g.setColor(getRandColor(220,250));
        g.fillRect(0, 0, w, h);
        // 加入干扰线条
        for (int i = 0; i < 8; i++) {
            g.setColor(getRandColor(40,150));
            Random random = new Random();
            int x = random.nextInt(w);
            int y = random.nextInt(h);
            int x1 = random.nextInt(w);
            int y1 = random.nextInt(h);
            g.drawLine(x, y, x1, y1);
        }
    }

    private static char[] codeSeq = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J',
            'K', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
            'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9' };
    private static String[] fontTypes = {"Arial","Arial Black","AvantGarde Bk BT","Calibri"};

    private static Random random = new Random();

    private void createCharacter(Graphics g, String s) {
       int len = s.length();
        for (int i = 0; i < len; i++) {
            g.setColor(new Color(50 + random.nextInt(100), 50 + random.nextInt(100), 50 + random.nextInt(100)));
            g.setFont(new Font(fontTypes[random.nextInt(fontTypes.length)],Font.BOLD,26));
            g.drawString(s.charAt(i)+ "", 15 * i + 5, 19 + random.nextInt(8));
        }
    }

    public static void main(String[] args) {
        Object s = "asdasd";
        if("asdasd".equals(s)){
            System.out.println(true);
        }
    }
}
